package com.herysoft.scm.log;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.herysoft.scm.biz.sys.UserBiz;
import com.herysoft.scm.model.sys.User;

public class UserAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
	private UserBiz userBiz;
	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}
	private String url;
	public void setUrl(String url) {
		this.url = url;
	}
	Logger log=Logger.getLogger(this.getClass());
	@SuppressWarnings("unchecked")
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		log.info(authentication.getName()+"["+request.getRemoteAddr()+"] login sucessful!");
		User user = userBiz.getUserByLoginName(authentication.getName());
		HttpSession session = request.getSession();
		ServletContext context = session.getServletContext();
		HashMap<String,User> onlineUsers = (HashMap<String,User>)context.getAttribute("OnlineUsers");
		if(onlineUsers==null)
			onlineUsers = new HashMap<String,User>();
		onlineUsers.put(session.getId(),user);
		context.setAttribute("OnlineUsers", onlineUsers);
		session.setAttribute("UserInfo", user);
		response.sendRedirect(request.getContextPath()+url);
	}
}
